package tjs.study.mini.spingmvcmini.config.tomact;

import lombok.SneakyThrows;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.annotation.HandlesTypes;
import java.util.Set;

/**
 * 对标以下类
 * {@link org.springframework.web.SpringServletContainerInitializer} @HandlesTypes(WebApplicationInitializer.class)
 *
 * @author nicky
 * @date 2021/9/7 下午12:21
 */
// 将WebApplicationInitializer的所有实现类，传入this.onStartup的webAppInitializerClasses形参
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {

    @SneakyThrows
    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) {
        System.out.println("tomact.Context.start回调ServletContainerInitializer.onStartup....");
        if (CollectionUtils.isEmpty(webAppInitializerClasses)) {
            servletContext.log("未定义WebApplicationInitializer");
            return;
        }

        for (Class<?> waiClass : webAppInitializerClasses) {
            WebApplicationInitializer webApplicationInitializer = (WebApplicationInitializer) ReflectionUtils.accessibleConstructor(waiClass).newInstance();
            webApplicationInitializer.onStartup(servletContext);
        }

        servletContext.log(webAppInitializerClasses.size() + " WebApplicationInitializer加载完成");
    }
}
